<?php

namespace App\Http\Controllers\queue;

use App\Models\Api\Queue;
use Illuminate\Database\Eloquent\Relations\MorphPivot;
use Illuminate\Support\Facades\Log;
use SebastianBergmann\CodeCoverage\Report\PHP;

class Worker
{
    private $queue;

    public function __construct()
    {
        $data = Queue::where('is_consume','=',false)->get();
        foreach ($data as $val) {
            $value = $val->toArray();
            echo("insert id {$value['id']}" . PHP_EOL);
            $val->is_accepted = true;
            $val->save();
        }
        $this->queue = PriorityTree::getIns();
        $this->queue->init($data->toArray());
    }

    function go()
    {
        echo('function is running' . PHP_EOL);
        while (true) {
            $data = Queue::where('is_accepted', '=', false)->get();//取出没有被队列接受的任务放入队列
            //$arrData = $data->toArray();
            foreach ($data as $val) {
                $value = $val->toArray();
                $v = $value['value'];
                if ($v === null)
                    $v = 0;
                echo("insert id {$value['id']}" . PHP_EOL);
                $this->queue->insert($value['id'], $v);
                $val->is_accepted = true;
                $val->save();
            }
            Queue::where('is_accepted', '=', false)->update(['is_accepted' => true]);
            $current = $this->queue->current();//取出任务 当任务到点之后就消费任务
            //echo("task length ".$this->queue->count().PHP_EOL);
            //task里面存储时间戳 当时间戳大于现在的时间戳 说明任务还没到执行的时候 休眠一下
            if ($current === null) {
                sleep(1);
                continue;
            }
            if ($current->getKey() > time()) {
                sleep(1);
                continue;
            }
            $task = $this->queue->extract();
            if ($task === null) {
                sleep(1);
                continue;
            }
            $pk = $task->getValue();
            Log::info($pk);
            echo("get a task {$pk}" . PHP_EOL);
        }
    }
}
